package com.zt.csp.shorturl.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zt.csp.shorturl.dto.ServiceResult;
import com.zt.csp.shorturl.entity.ShortUrl;
import com.zt.csp.shorturl.entity.ViewLog;
import com.zt.csp.shorturl.mapper.ShortUrlMapper;
import com.zt.csp.shorturl.mapper.ViewLogMapper;
import com.zt.csp.shorturl.service.ViewLogService;
import com.zt.csp.shorturl.utils.ConvertRadix;
import com.zt.csp.shorturl.utils.ThreadLocalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Created by zt on 2018/4/27 0027
 */
@Service
public class ViewLogServiceImpl implements ViewLogService {
    private static final Logger logger = LoggerFactory.getLogger(ViewLogServiceImpl.class);

    @Autowired
    private ViewLogMapper viewLogMapper;

    @Autowired
    private ShortUrlMapper shortUrlMapper;

    @Override
    public ServiceResult saveLog(ViewLog viewLog) {
        logger.info("插入短链接访问日志：{}", viewLog.toString());
        Integer insert = viewLogMapper.insert(viewLog);
        if (insert > 0) {
            return ServiceResult.ok(null);
        } else {
            return ServiceResult.failed(10001, "插入失败");
        }
    }

    @Override
    public ServiceResult list(int page, int pageSize, String code) {
        String userId = ThreadLocalUtils.USER_THREAD_LOCAL.get();
        if (StringUtils.isEmpty(userId)) {
            return ServiceResult.NO_LOGIN;
        }
        ShortUrl shortUrl = shortUrlMapper.selectById(ConvertRadix.N_to_10(code, 62));
        if (shortUrl == null) {
            return ServiceResult.failed(10005, "找不到该短链接");
        }
        if (!userId.equals(shortUrl.getCreatedBy())) {
            return ServiceResult.failed(10006, "不是当前用户创建的短链接，没有查看权限");
        }
        EntityWrapper<ViewLog> wrapper = new EntityWrapper<>();
        wrapper.andNew().eq("req_short_id", shortUrl.getId());
        wrapper.orderBy("req_time", false);
        Page<ViewLog> pageEntity = new Page<>();
        pageEntity.setSize(pageSize);
        pageEntity.setCurrent(page);
        pageEntity.setRecords(viewLogMapper.selectPage(pageEntity, wrapper));
        return ServiceResult.ok(pageEntity);
    }
}
